<?php
/**
 * Permission
 * Check user's permission
 * @author longpt
 * @version 
 */

require_once "BaseModel.php";
require_once 'DBUtils.php';
require_once 'RolesInheritance.php';

class Permission extends BaseModel {
	/**
	 * The default table name 
	 */
	protected $_name = 'permissions';
	protected $_primary = array ('role_id', 'controller', 'action' );
	protected $_cols = array ('role_id', 'controller', 'action', 'block' );
	protected $data = array ();
	// all value will be setup here
	public function check($role_id, $controller, $action) {
		$result = $this->checkCurrent($role_id, $controller, $action);
		if ($result == true)	{
			return true;
		}
		
		//check for its subrole's permission
		$rolesInherit = new RolesInheritance($role_id);
		$parentRole = $rolesInherit->getParentRole();
		if ($parentRole == null)	{
			return null;
		}
		return $this->check($parentRole, $controller, $action);
	}
	
	public function abstractLoad($id) {
	
	}
	
	public function createDefaultData() {
	
	}
	
	public function checkCurrent($role_id, $controller, $action) {
		$stmt = $this->select ()->where ( 'role_id = :_roleId' )->where ( '(controller = :_controller and action = :_action) or (controller = :_controller and action = "*") or (controller = "*")' )->where ( 'block=0' )->bind ( array (':_roleId' => $role_id, ':_controller' => $controller, ':_action' => $action ) );
		$result = $this->getAdapter ()->fetchAll ( $stmt, array (), Zend_Db::FETCH_OBJ );
		if (count ( $result ) > 0) {
			$this->data = $result;
			return true;
		} else {
			return false;
		}
	}
}

